package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.constant.MessageConstant;
import com.itheima.health.entity.Result;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.ReportService;
import com.itheima.health.service.SetmealService;
<<<<<<< HEAD
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
=======
import com.itheima.health.utils.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
>>>>>>> adc48831cde55357ef0420c5deac2882fa85ad7a
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
<<<<<<< HEAD
=======
import java.text.Format;
>>>>>>> adc48831cde55357ef0420c5deac2882fa85ad7a
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName CheckItemController
 * @Description TODO
 * @Author ly
 * @Company 深圳黑马程序员
 * @Date 2019/8/20 16:03
 * @Version V1.0
 */
@RestController
@RequestMapping(value = "/report")
public class ReportController {

    // dubbo消费者
    @Reference
    MemberService memberService;

    @Reference
    SetmealService setmealService;

    @Reference
    ReportService reportService;


    // 统计查询每个月注册会员的数量折线图
    @RequestMapping(value = "/getMemberReport")
    public Result getMemberReport(){
        try {
<<<<<<< HEAD
            /**
             * 组织Map<String,Object>
             * map：   key             value
             *          months          List<String>   (["2018-12","2019-01","2019-02","2019-03","2019-04","2019-05"])
             *          memberCount     List<Integer>  ([5, 20, 36, 40, 50, 60])
             */
=======
>>>>>>> adc48831cde55357ef0420c5deac2882fa85ad7a
            Map<String,Object> map = new HashMap<String,Object>();
            // 组织months，封装最近1年内的月份查询
            List<String> monthsList = new ArrayList<String>();
            Calendar instance = Calendar.getInstance();
            instance.add(Calendar.MONTH,-12); // 根据当前时间，获取前12个月的日历（日历对象2018-8）
            // 遍历
            for (int i = 0; i < 12; i++) {
                instance.add(Calendar.MONTH,1); //2018-9 2018-10 2018-11
                monthsList.add(new SimpleDateFormat("yyyy-MM").format(instance.getTime()));
            }
            map.put("months",monthsList);

            List<Integer> memberCountList = memberService.findMemberCountByRegTime(monthsList);
            map.put("memberCount",memberCountList);
            // 成功
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            // 成功
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }

    }

    // 统计套餐预约人数占比（饼图）
    @RequestMapping(value = "/getSetmealReport")
    public Result getSetmealReport(){
        try {
            /**
             * Result(flag,message,data)
                    data = Map<String,Object>
                             map
                             key                                      value
                             setmealNames                List<String>
                             setmealCount                List<Map<String,Object>>
                                                         key:value,name
                                                         value:3  传智三八节福利套餐
             */
            Map<String,Object> map = new HashMap<String,Object>();
            // 组织套餐名称+套餐名称对应的数据
            List<Map<String,Object>> setmealCount = setmealService.findSetmealCountByOrder();
            map.put("setmealCount",setmealCount);
            // 组织套餐名称集合（格式：List<"传智三八节福利套餐","传智入职套餐">）
            List<String> setmealNames = new ArrayList<String>();
            for (Map<String, Object> stringObjectMap : setmealCount) {
                String name = (String)stringObjectMap.get("name");
                setmealNames.add(name);
            }
            map.put("setmealNames",setmealNames);
            // 成功
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            // 成功
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }

    }

    // 运营数据统计（页面）
    @RequestMapping(value = "/getBusinessReportData")
    public Result getBusinessReportData(){
        try {
            Map<String,Object> map = reportService.getBusinessReportData();
            // 成功
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            // 成功
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }

    }

    // 运营数据统计（Excel报表）
    @RequestMapping(value = "/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        try {
            Map<String,Object> map = reportService.getBusinessReportData();
            // 1：获取数据
            String reportDate = (String) map.get("reportDate");
            Integer todayNewMember = (Integer)map.get("todayNewMember");
            Integer totalMember = (Integer)map.get("totalMember");
            Integer thisWeekNewMember = (Integer)map.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer)map.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) map.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) map.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) map.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) map.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) map.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) map.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) map.get("hotSetmeal");
            // 2：读取项目路径下存放template/report_template.xlsx
            String path = request.getSession().getServletContext().getRealPath("/template") + File.separator + "report_template.xlsx";
            // 3：使用POI的技术，完成导出
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(path)));
            XSSFSheet sheet = workbook.getSheetAt(0);
            // 当前日期
            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);
            // 今日新增会员数+总会员数
            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);
            row.getCell(7).setCellValue(totalMember);
            // 本周新增会员数+本月新增会员数
            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);
            row.getCell(7).setCellValue(thisMonthNewMember);

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int rowNum = 12;
            for(Map map1 : hotSetmeal){//热门套餐
                String name = (String) map1.get("name");
                Long setmeal_count = (Long) map1.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map1.get("proportion");
                row = sheet.getRow(rowNum ++);
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比
            }
            // 4：将XSSFWorkbook写到IO流
            ServletOutputStream os = response.getOutputStream();
            // 以什么样的文件形式输出（导出、下载）必须要指定
            //（1）下载的数据类型（excel类型）
            response.setContentType("application/vnd.ms-excel");
            //（2）下载的形式（第一种：附件；第二种：内连(inline)）
            response.setHeader("Content-Disposition","attachment;filename=export.xls");
            workbook.write(os);
            os.flush();
            os.close();
            workbook.close();
            // 成功
            return null; // 使用IO流的形式输出文件（下载、打开）
        } catch (Exception e) {
            e.printStackTrace();
            // 成功
            return null;
        }

    }
<<<<<<< HEAD
=======

    @RequestMapping("/queryMember")
    public Result queryMember (@RequestBody Map map){
        try {
            Map<String,Object> monthMap = new HashMap<String,Object>();
            String begin = (String) map.get("begin");
            String end = (String) map.get("end");
            List<String> monthList = DateUtils.getMonthBetween(begin, end, "yyyy-MM");
            monthMap.put("months",monthList);
            List<Integer> memberCountList = memberService.findMemberCountByRegTime(monthList);
            monthMap.put("memberCount",memberCountList);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,monthMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
>>>>>>> adc48831cde55357ef0420c5deac2882fa85ad7a
}
